import React from 'react';
import { Modal, Spin, Form, TreeSelect } from 'antd';
import ProForm, {
  ProFormText,
  ProFormTextArea,
  ProFormSwitch,
} from '@ant-design/pro-form';
import { useState } from 'react';
import { getOrganizationTreeSelectData } from '../service';
import { useRequestHandle } from '@/utils/utils';
import { useUpdateEffect } from '@umijs/hooks';

const SaveForm = (props) => {
  const { modalVisible, onCancel, onSubmit, loading, record, organizationId, organizationName } = props;

  const [orgSelectData, setOrgSelectData] = useState([]);
  const getOrgSelectHandler = useRequestHandle(getOrganizationTreeSelectData, (data) => {
    setOrgSelectData(data);
  });

  useUpdateEffect(() => {
    if (modalVisible) {
      getOrgSelectHandler.run({ companyId: organizationId });
    }
  }, [modalVisible]);
  return (
    <Modal
      destroyOnClose
      title={record.id ? '修改部门' : '新增部门'}
      open={modalVisible}
      onCancel={() => onCancel()}
      footer={null}
    >
      <Spin tip="正在处理..." spinning={loading}>
        <ProForm
          onFinish={async (value) => {
            const params = value;
            params.id = record.id;
            params.organizationType = 1;
            if (params.parentId === undefined) {
              params.parentId = organizationId;
            }
            await onSubmit(value);
          }}
          initialValues={{
            status: true,
            companyType: 0,
            ...record,
            organizationName,
            costCenter: !record.costCenter ? "无" : record.costCenter,
            parentId: record.parentId === record.companyId ? undefined : record.parentId,
          }}
        >
        
          <Form.Item
            name="parentId"
            label="上级组织"
          >
            <TreeSelect
              allowClear={true}
              style={{ width: '100%' }}
              dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
              treeData={orgSelectData}
              placeholder="请选择上级组织"
              treeDefaultExpandAll
            />
          </Form.Item>
          <ProFormText
            name="name"
            label="部门名称"
            fieldProps={{
              allowClear: true,
            }}
            placeholder="请输入部门名称"
            rules={[{ required: true, message: '请输入部门名称！' }]}
          />

          <ProFormTextArea
            name="remarks"
            label="备注"
            placeholder="请输入备注"
            fieldProps={{
              allowClear: true,
            }}
          />
          {!record.id && (
            <ProFormSwitch
              name="status"
              label="状态"
              checkedChildren="启用"
              unCheckedChildren="禁用"
            />
          )}
        </ProForm>
      </Spin>
    </Modal>
  );
};

export default SaveForm;
